package com.ztjava.auth.controller.member.minp;

import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Duang;
import com.jfinal.kit.HttpKit;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.ztjava.auth.model.AuthThird;
import com.ztjava.auth.model.AuthUser;
import com.ztjava.auth.service.AuthService;
import com.ztjava.core.Constant;
import com.ztjava.core.annotation.ControllerClass;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.client.member.ApiClient;
import com.ztjava.core.tool.ViewTool;
import com.ztjava.ext.auth.annotation.UserController;
import com.ztjava.ext.auth.tool.AuthTool;
@ControllerClass(path="/auth/minp",client=ApiClient.class)
@UserController(portal=Constant.P_MEMBER,token=AuthTool.para)
public class AuthApiMinpController extends BaseController{
	private static final String AUTHTYPE = "AUTH_MEMBER_THIRD_AUTHTYPE";
	private static AuthService authService = Duang.duang(AuthService.class);
	//不需要AppMethod，自身可以防止被其它APP利用
	public void login(){
		String code = getPara("code");
		if(code==null||code.equals("")){
			renderError("code不存在");
			return;
		}
		String result = "{\"errcode\": 0,\"errmsg\":\"网络连接失败\"}";
		try{
			result = HttpKit.get("https://api.weixin.qq.com/sns/jscode2session"
					+ "?appid="+ViewTool.param("AUTH_MEMBER_THIRD_MINP_APPID")
					+ "&secret="+ViewTool.param("AUTH_MEMBER_THIRD_MINP_SECRET")
					+ "&js_code="+code+"&grant_type=authorization_code");
		}catch (Exception e) {
			e.printStackTrace();
		}
		JSONObject rjson = JSONObject.parseObject(result);
		if(rjson.get("errcode")!=null){
			setAttr(Constant.RESULT, Constant.ERROR);
			setAttr(Constant.MESSAGE, rjson.getString("errmsg"));
			renderJson(new String[]{Constant.RESULT,Constant.MESSAGE});
			return;
		}
		String openid = rjson.getString("openid");
		String session_key = rjson.getString("session_key");
		Cache cache = Redis.use();
		if(cache.exists(Constant.R_PRE+"AUTH:MINI:SESSION_KEY:"+session_key)&&cache.exists(cache.get(Constant.R_PRE+"AUTH:MINI:SESSION_KEY:"+session_key))){
			String token = cache.get(Constant.R_PRE+"AUTH:MINI:SESSION_KEY:"+session_key);
			cache.expire(Constant.R_PRE+"AUTH:MINI:SESSION_KEY:"+session_key, 3600*24*7);
			cache.expire(token, 3600*24*7);
			setAttr(Constant.RESULT, Constant.SUCCESS);
			setAttr("token", token);
			setAttr("expire",3600*24*7);
			renderJson(new String[]{Constant.RESULT,"token","expire"});
			return;
		}
		String unionid = null;
		if(rjson.get("unionid")!=null){
			unionid = rjson.getString("unionid");
		}
		AuthThird authThird = authService.getThirdByCodeAndUnionid(Constant.P_MEMBER,AuthThird.MINP, openid,unionid);
		if(authThird.get("unionid")==null&&unionid!=null) authThird.set("unionid", unionid);

		if(authThird.get("user_id")!=null){
			AuthUser authUser = AuthUser.dao.findById(authThird.getInt("user_id"));
			if(authUser==null||authUser.getStr("enable_flag").equals("F")){
				setAttr(Constant.RESULT, Constant.ERROR);
				setAttr(Constant.MESSAGE, "账户被删除或被停用");
				renderJson(new String[]{Constant.RESULT,Constant.MESSAGE});
				return;
			}
			authThird.set("last_login_time",new Timestamp(new Date().getTime())).update();
			String token = AuthTool.createUserSession(authService.userToSession(authUser), 3600*24*7,null);
			cache.setex(Constant.R_PRE+"AUTH:MINI:SESSION_KEY:"+session_key, 3600*24*7, token);
			setAttr(Constant.RESULT, Constant.SUCCESS);
			setAttr("token", token);
			setAttr("expire",3600*24*7);
			renderJson(new String[]{Constant.RESULT,"token","expire"});
			return;
		}

		//未绑定会员
		if(!ViewTool.param("AUTH_"+Constant.P_MEMBER+"_REGISTER_ONOFF").equals("ON")){
			setAttr(Constant.RESULT, Constant.ERROR);
			setAttr(Constant.MESSAGE, "已停止注册！");
			renderJson(new String[]{Constant.RESULT,Constant.MESSAGE});
			return;
		}		
		Map<String,String> userMap = new HashMap<>();
		switch (ViewTool.param(AUTHTYPE)) {
			case "AUTO":
				AuthUser authUser = authService.insertUserByThird(authThird,userMap);
				cache.hset(Constant.R_PRE+"AUTH:THIRD:WEIXIN", authUser.getInt("id"), openid);
				AuthTool.createUserSession(authService.userToSession(authUser),3600 * 24, getResponse(),null);

				String token = AuthTool.createUserSession(authService.userToSession(authUser), 3600*24*7,null);
				cache.setex(Constant.R_PRE+"AUTH:MINI:SESSION_KEY:"+session_key, 3600*24*7, token);
				setAttr(Constant.RESULT, Constant.SUCCESS);
				setAttr("token", token);
				setAttr("expire",3600*24*7);
				renderJson(new String[]{Constant.RESULT,"token","expire"});
				return;
			case "BINDING":
			default:
				break;
		}
	}
}
